package com.qiezi.project.activity;


import android.graphics.Typeface;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.RadioGroup;
import android.widget.TextView;

import com.alipay.sdk.app.PayTask;
import com.hjq.dialog.WaitDialog;
import com.qiezi.App;
import com.qiezi.R;
import com.qiezi.base.BaseMvpActivity;
import com.qiezi.base.BaseRecyclerAdapter;
import com.qiezi.bean.MemberTypeBean;
import com.qiezi.mvp.CreatePresenter;
import com.qiezi.project.contract.VipCenterContract;
import com.qiezi.project.decoration.RecyclerItemDecoration;
import com.qiezi.project.view.PriceView;
import com.qiezi.util.pay.PayResult;
import com.tencent.mm.opensdk.modelpay.PayReq;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;

import java.util.ArrayList;
import java.util.Map;

import butterknife.BindView;
import es.dmoral.toasty.Toasty;

@CreatePresenter(presenter = VipCenterContract.Presenter.class)
public class VipCenterActivity extends BaseMvpActivity<VipCenterContract.Presenter> implements VipCenterContract.View,View.OnClickListener {


    public static class VipAdapter extends BaseRecyclerAdapter<MemberTypeBean> {

        public class VH extends Holder{

            PriceView pv;

            public VH(View itemView) {
                super(itemView);
                pv = itemView.findViewById(R.id.pv_price);
            }

            public void setData(MemberTypeBean data){
                pv.setTitle(data.getName());
                pv.setHint(data.getRemark());
                pv.setOldPrice(data.getAmount());
                pv.setNewPrice(data.getPay_amount());
                pv.setRecommend(data.isIs_recommend());
            }
        }

        @Override
        public RecyclerView.ViewHolder onCreate(ViewGroup viewGroup, int viewType) {
            View v = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.item_vip, viewGroup, false);
            return new VH(v);
        }

        @Override
        public void onBind(RecyclerView.ViewHolder viewHolder, int RealPosition, MemberTypeBean data) {
            ((VH)viewHolder).setData(data);
        }
    }


    @BindView(R.id.tv_back)
    TextView tvBack;

    @BindView(R.id.ic_alipay)
    TextView icAlipay;

    @BindView(R.id.ic_wechat)
    TextView icWechat;

    @BindView(R.id.rg_payment)
    RadioGroup rgPayment;


    @BindView(R.id.tv_userName)
    TextView tvUsername;

    @BindView(R.id.rcv_vip)
    RecyclerView rcv;

    @BindView(R.id.tv_endtime)
    TextView tvEndTime;

    enum PayType{
        alipay(1),wechat(2);

        Integer type;
        PayType(Integer type){
            this.type = type;
        }

        public Integer getType() {
            return type;
        }
    }

    private PayType payType = PayType.alipay;

    @Override
    protected int getLayoutRes() {
        return R.layout.activity_vip_center;
    }

    private void setTypeface(){
        Typeface iconfont = Typeface.createFromAsset(getAssets(), "fonts/iconfont.ttf");
        tvBack.setTypeface(iconfont);
        icAlipay.setTypeface(iconfont);
        icWechat.setTypeface(iconfont);
    }
    VipAdapter adapter;
    @Override
    protected void initData(Bundle saveBundle) {
        setTypeface();
        adapter = new VipAdapter();
        View v = LayoutInflater.from(this).inflate(R.layout.item_footer_vip,null);
        adapter.setFooterView(v);
        adapter.setEmptyViewDef(this,-1);
        adapter.setEmptyVisibility(View.VISIBLE);
        adapter.setEmptyText("加载中...");
        rcv.setLayoutManager(new LinearLayoutManager(this,LinearLayoutManager.VERTICAL,false));
        rcv.setAdapter(adapter);
        rcv.addItemDecoration(new RecyclerItemDecoration(10,1));
        rcv.setItemAnimator(new DefaultItemAnimator());

        tvUsername.setText(App.getInstance().getUserName());
        getPresenter().loadData();
    }

    @Override
    protected void initListener() {
        tvBack.setOnClickListener(this);
        rgPayment.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                if (checkedId == R.id.rb_alipay){
                    payType = PayType.alipay;
                    log("alipay");
                }else if (checkedId == R.id.rb_wechat){
                    payType = PayType.wechat;
                    log("wechat");
                }
            }
        });

        adapter.setOnItemClickListener(new BaseRecyclerAdapter.OnItemClickListener<MemberTypeBean>() {
            @Override
            public void onItemClick(int position, MemberTypeBean data) {
                buyMember(data.getId());
            }
        });
    }


    private WaitDialog.Builder dialog;

    private void buyMember(String id){
        if (dialog != null)dialog.dismiss();
        dialog = new WaitDialog.Builder(this).setMessage("支付中...");
        dialog.show();
        getPresenter().buyMember(id,payType.getType());
    }



    private Handler mHandler = new Handler() {
        public void handleMessage(Message msg) {
            PayResult payResult = new PayResult((Map<String, String>) msg.obj);
            String resultInfo = payResult.getResult();// 同步返回需要验证的信息
            String resultStatus = payResult.getResultStatus();
            // 判断resultStatus 为9000则代表支付成功
            if (TextUtils.equals(resultStatus, "9000")) {
                // 该笔订单是否真实支付成功，需要依赖服务端的异步通知。
//                showAlert(PayDemoActivity.this, getString(R.string.pay_success) + payResult);
            } else {
                // 该笔订单真实的支付结果，需要依赖服务端的异步通知。
//                showAlert(PayDemoActivity.this, getString(R.string.pay_failed) + payResult);
            }
            Toasty.normal(VipCenterActivity.this,payResult.getResult());
        }
    };

    Runnable payRunnable = new Runnable() {

        @Override
        public void run() {
            PayTask alipay = new PayTask(VipCenterActivity.this);
            Map<String,String> result = alipay.payV2(orderInfo,true);

            Message msg = new Message();
            msg.what = payType.getType();
            msg.obj = result;
            mHandler.sendMessage(msg);
        }
    };

    private String orderInfo;

    @Override
    public void onBuyMember() {
        //这里应该调用支付宝或微信支付
        if (payType == PayType.alipay){
            orderInfo = "";
            Thread payThread = new Thread(payRunnable);
            payThread.start();
        }else {
            IWXAPI api= WXAPIFactory.createWXAPI(this, "wxAPPID",false);//填写自己的APPID
            api.registerApp("wxAPPID");//填写自己的APPID，注册本身APP
            PayReq req = new PayReq();//PayReq就是订单信息对象
//给req对象赋值
            req.appId = "appid";//APPID
            req.partnerId = "partnerid";//    商户号
            req.prepayId = "prepayid";//  预付款ID
            req.nonceStr = "getRoundString()";//随机数
            req.timeStamp = "getTimeStamp()";//时间戳
            req.sign = "sign";//签名
            req.packageValue = "Sign=WXPay";//固定值Sign=WXPay

            api.sendReq(req);
        }
        complete();
    }

    @Override
    public void complete() {
        super.complete();
        if (dialog != null)dialog.dismiss();
    }

    @Override
    public void resultData(ArrayList<MemberTypeBean> data, boolean isOpen, String endTime) {
        tvEndTime.setText(isOpen ? endTime : "您还不是会员");
        adapter.setDatas(data);
    }


    @Override
    public void showError(String msg) {
        super.showError(msg);
        adapter.setEmptyText("加载失败，请稍后重试");
        complete();
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.tv_back:
                finish();
                break;
        }
    }

    @Override
    protected void onDestroy() {
        mHandler.removeCallbacksAndMessages(null);
        super.onDestroy();
    }
}
